var workshopId = "";
var selectedStaffs = [];

layui.config({
    base: basePath,
    version: skyeyeVersion
}).extend({
    window: 'js/winui.window'
}).define(['window', 'table', 'jquery', 'winui', 'form'], function (exports) {
    winui.renderColor();
    var $ = layui.$,
        form = layui.form;

    // 获取URL参数中的车间ID
    workshopId = GetUrlParam("workshopId");

    // 设置车间ID到表单中
    $("#farmId").val(workshopId);

    // 初始化表单
    initForm();

    // 初始化表单
    function initForm() {
        // 加载工位列表
        loadWorkstationsList();

        // 绑定事件
        bindEvents();
    }

    // 绑定事件
    function bindEvents() {
        // 员工选择框点击事件
        $("body").on("click", "#staffInfo", function () {
            openStaffSelector();
        });

        // 保存按钮点击事件
        $("body").on("click", "#saveBean", function () {
            // 获取表单数据
            var formData = {
                farmId: $("#farmId").val() || workshopId,
                workstationId: $("#workstationId").val(),
                staffIds: $("#staffIds").val()
            };

            // 保存员工分配
            saveStaffAssignment(formData);
        });

        // 取消按钮点击事件
        $("body").on("click", "#cancle", function () {
            closeWindow();
        });

        // 删除员工事件
        $("body").on("click", ".staff-badge-close", function () {
            var staffId = $(this).closest('.staff-badge').data('id');
            removeStaff(staffId);
        });
    }

    // 保存员工分配
    function saveStaffAssignment(formData) {
        // 验证表单
        if (!formData.farmId) {
            formData.farmId = workshopId;
        }

        if (!formData.workstationId) {
            winui.window.msg('请选择工位', { icon: 2, time: 2000 });
            return false;
        }

        if (!formData.staffIds || formData.staffIds.trim() === '') {
            winui.window.msg('请至少选择一名员工', { icon: 2, time: 2000 });
            return false;
        }

        // 获取员工ID列表
        var staffIds = [];
        try {
            staffIds = JSON.parse(formData.staffIds);
        } catch (e) {
            if (formData.staffIds) {
                staffIds = [formData.staffIds];
            }
        }

        if (!staffIds || staffIds.length === 0) {
            winui.window.msg('请至少选择一名员工', { icon: 2, time: 2000 });
            return false;
        }

        // 显示加载中状态
        var loadIndex = layer.load(1, {
            shade: [0.1, '#fff']
        });

        // 构建staffIdAndStationIdList
        var staffIdAndStationIdList = [];
        staffIds.forEach(function (staffId) {
            staffIdAndStationIdList.push({
                staffId: staffId,
                farmStationId: formData.workstationId
            });
        });

        // 构建参数
        var params = {
            farmId: formData.farmId,
            staffIdAndStationIdList: JSON.stringify(staffIdAndStationIdList)
        };

        // 发送请求
        AjaxPostUtil.request({
            url: sysMainMation.erpBasePath + "insertFarmStaff",
            params: params,
            type: 'json',
            method: "POST",
            callback: function (json) {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
                parent.refreshCode = '0';
            }
        });
    }

    // 加载工位列表
    function loadWorkstationsList() {
        AjaxPostUtil.request({
            url: sysMainMation.erpBasePath + "queryFarmStationList",
            params: {
                page: 1,
                limit: 9999,
                farmId: workshopId  // 使用farmId作为查询参数
            },
            type: 'json',
            method: 'POST',
            callback: function (json) {
                if (json.rows && json.rows.length > 0) {
                    var workstations = json.rows;
                    var optionsHtml = '<option value="">请选择工位</option>';

                    // 构建工位选项
                    $.each(workstations, function (index, item) {
                        optionsHtml += '<option value="' + item.id + '">' + item.name + '</option>';
                    });

                    // 更新下拉框选项
                    $("#workstationId").html(optionsHtml);
                    form.render('select');
                } else {
                    winui.window.msg('未找到工位信息', { icon: 0, time: 2000 });
                }
            }
        });
    }

    // 打开员工选择器
    function openStaffSelector() {
        // 设置员工选择为多选模式
        systemCommonUtil.userStaffCheckType = true;
        systemCommonUtil.checkStaffMation = [];

        // 如果已经选择了员工，传入当前选择
        if (selectedStaffs.length > 0) {
            systemCommonUtil.checkStaffMation = selectedStaffs;
        }

        // 打开员工选择页面
        systemCommonUtil.openSysAllUserStaffChoosePage(function (checkStaffMation) {
            if (checkStaffMation && checkStaffMation.length > 0) {
                selectedStaffs = checkStaffMation;

                // 更新员工显示
                updateStaffDisplay();

                // 更新员工ID
                updateStaffIds();
            }
        });
    }

    // 更新员工显示
    function updateStaffDisplay() {
        // 隐藏占位符
        if (selectedStaffs.length > 0) {
            $("#staffInfo .placeholder").hide();
        } else {
            $("#staffInfo .placeholder").show();
        }

        // 更新员工列表
        var $staffList = $("#staffList");
        $staffList.empty();

        // 添加员工标签
        selectedStaffs.forEach(function (staff) {
            var staffHtml = `
                <span class="staff-badge" data-id="${staff.id}">
                    ${staff.userName || '未知员工'} 
                    <i class="layui-icon layui-icon-close staff-badge-close"></i>
                </span>
            `;
            $staffList.append(staffHtml);
        });
    }

    // 更新员工ID
    function updateStaffIds() {
        var staffIds = selectedStaffs.map(function (staff) {
            return staff.id;
        });

        $("#staffIds").val(JSON.stringify(staffIds));
    }

    // 删除员工
    function removeStaff(staffId) {
        // 从数组中移除
        selectedStaffs = selectedStaffs.filter(function (staff) {
            return staff.id !== staffId;
        });

        // 更新显示
        updateStaffDisplay();

        // 更新员工ID
        updateStaffIds();

        // 如果没有员工了，显示占位符
        if (selectedStaffs.length === 0) {
            $("#staffInfo .placeholder").show();
        }
    }

    // 关闭窗口
    function closeWindow() {
        parent.layer.close(parent.layer.getFrameIndex(window.name));
        return false;
    }

    exports('write', {});
});

